package com.hhw.androidhttpserver;

import android.app.Activity;
import android.os.Bundle;

import java.net.InetAddress;

public class MainActivity extends Activity {

    private HttpServer mHttpServer = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new Runnable() {
            @Override
            public void run() {
                //不能在主线程启动Http服务端
                startHttpServer();
            }
        }).start();

    }

    private void startHttpServer() {
        if (mHttpServer == null){
            try {
                final String ip = InetAddress.getLocalHost().getHostAddress();
                final int port = 9988;
                mHttpServer = new HttpServer(ip,port);
                mHttpServer.start();

                System.out.println("onCreate http start ok :" + mHttpServer.hostname + ":" + mHttpServer.myPort);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

    private void closeHttpServer(){
        if (mHttpServer != null){
            mHttpServer.stop();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeHttpServer();
    }
}